package com.springcloud.service.impl;

import com.springcloud.dao.UserDao;
import com.springcloud.entities.LoginUser;
import com.springcloud.entities.User;
import com.springcloud.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserDao userDao;
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public int createUser(User user) {
        int rs = userDao.createUser(user);
        User save = mongoTemplate.save(user);
        logger.debug(save.toString());
        return rs;
    }

    @Override
    public User login(LoginUser user) {

        Query query = new Query();
        query.addCriteria(
                new Criteria().andOperator(
                        Criteria.where("loginName").is(user.getLoginName()),
                        Criteria.where("loginPWD").is(user.getLoginPWD())
                )
        );


        List<User> listmg = mongoTemplate.find(query, User.class);
        logger.debug(listmg.toString());
        List<User> list = userDao.login(user);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public User getLoginPWD(User user) {
        List<User> list = userDao.getLoginPWD(user);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
